<template>
  <view :style="colorStyle">
    <view class="infobox1">
      <view class="info1">
        <view class="label"> 联系人姓名 </view>
        <view class="input">
          <input
            type="text"
            placeholder-class="placeholder"
            placeholder="请输入联系人姓名"
            v-model="from.consignee"
          />
        </view>
      </view>
      <view class="info1">
        <view class="label"> 手机号码 </view>
        <view class="input">
          <input
            type="number"
            maxlength="11"
            placeholder-class="placeholder"
            placeholder="请输入手机号码"
            v-model="from.mobile"
          />
        </view>
      </view>
      <view class="info1" @click="chooseLocation">
        <view class="label"> 所在地区 </view>
        <view class="input">
          <view
            class=""
            v-if="!from.province"
            style="margin: 0 50rpx 0 0; color: #858585; font-size: 32rpx"
          >
            请选择所在地区
          </view>
          <view
            class=""
            v-if="from.province"
            style="text-align: left; margin: 0 30rpx 0 0; color: #1f1f1f"
          >
            {{ from.province }}{{ from.city }}{{ from.district }}
          </view>
          <view class="right">
            <image src="@/static/img18.png" mode="widthFix" />
          </view>
        </view>
      </view>
      <!-- <view class="info1" @click="show = true">
        <view class="label"> 所在地区 </view>
        <view class="input">
          <view
            class=""
            v-if="!from.province"
            style="margin: 0 50rpx 0 0; color: #858585; font-size: 32rpx"
          >
            请选择所在地区
          </view>
          <view
            class=""
            v-if="from.province"
            style="text-align: left; margin: 0 30rpx 0 0; color: #1f1f1f"
          >
            {{ from.province }}{{ from.city }}{{ from.district }}
          </view>
          <view class="right">
            <image src="@/static/img18.png" mode="widthFix" />
          </view>
        </view>
      </view> -->
      <view class="info1">
        <view class="label"> 详细地址 </view>
        <view class="input">
          <input
            type="text"
            placeholder-class="placeholder"
            placeholder="请输入详细地址精确到门牌号"
            v-model="from.address"
          />
        </view>
      </view>
      <view class="info1 flex aitems between" style="border: none">
        <view class="label"> 设为默认地址 </view>
        <view class="icon" @click="defaultChange">
          <switch
            :checked="from.isDefault"
            color="var(--view-theme)"
            style="transform: scale(0.8)"
          />
        </view>
      </view>
    </view>
    <view class="globalBtn" @click="save">
      <view class="block1">
        {{ submitText }}
      </view>
    </view>

    <view style="height: 200rpx"></view>

    <u-picker
      itemHeight="80"
      :loading="loading"
      :show="show"
      ref="uPicker"
      :columns="columns"
      @confirm="confirm"
      @change="changeHandler"
      @cancel="show = false"
    ></u-picker>
  </view>
</template>

<script>
import colors from "@/mixins/color";
const app = getApp();

import { msg, back, showModal, go, loading, backtime } from "@/utils/wxAPI";

import { regionList, addressSubmit, addressInfo } from "@/servers/servers.js";

import { HTTP_STATUS, config } from "@/servers/config.js";

import { isvalidatemobile } from "@/utils/validate.js";

// import {
// 	tofixed2,
// 	wan,
// } from '@/utils/util'
export default {
  mixins: [colors],
  data() {
    return {
      options: {},
      show: false,
      from: {
        id: "",
        consignee: "",
        mobile: "",
        isDefault: false,
        province: "",
        provinceId: "",
        city: "",
        cityId: "",
        district: "",
        districtId: "",
        address: "",
        lat: "",
        lng: "",
      },
      submitText: "保存收货地址",
      columns: [[], [], []],
      levelregion: [],
      leve2region: [],
      leve3region: [],
      loading: true,

      address: "",
      selectorObj: [],
      defaultvalue: [0, 0, 0],
    };
  },
  async onLoad(options) {
    this.options = options;
    // await this.handleRegionList();

    if (options.id) {
      this.submitText = "修改收货地址";
      addressInfo({
        id: options.id,
      }).then((res) => {
        let {
          consignee,
          mobile,
          isDefault,
          province,
          provinceId,
          city,
          cityId,
          district,
          districtId,
          address,
          lat,
          lng,
        } = res.data.data;
        this.from.consignee = consignee;
        this.from.mobile = mobile;
        this.from.isDefault = isDefault ? true : false;
        this.from.province = province;
        this.from.provinceId = provinceId;
        this.from.city = city;
        this.from.cityId = cityId;
        this.from.district = district;
        this.from.districtId = districtId;
        this.from.address = address;
        this.from.lat = lat;
        this.from.lng = lng;
      });
    }
    if (app.globalData.token) {
      //有token执行
      //这里推荐执行分页
    } else {
      //没token执行
      // await islogin();
    }
  },
  async onShow() {
    if (app.globalData.token) {
      //有token执行
      //这里执行返回页面得执行
      //不推荐执行分页
      //执行需要回显得接口
      if (uni.getStorageSync("ref")) {
        // uni.removeStorageSync('ref')
        // this.current = 1;
        //刷新分页
      }
    }
  },
  /**** 方法层 ****/
  methods: {
    async handleRegionList(code, index) {
      loading();
      let { data } = await regionList({
        parentCode: "00",
        regionLevel: 1,
      });
      if (data.code == HTTP_STATUS.RUSELT_SUCCESS) {
        let data1 = [];
        data.data.map((item) => {
          data1.push(item.name);
        });
        this.columns[0] = data1;
        this.levelregion = data.data;
        this.$refs.uPicker.setColumnValues(0, data1);
        regionList({
          parentCode: data.data[0].code,
        }).then((res) => {
          let data1 = [];
          res.data.data.map((item) => {
            data1.push(item.name);
          });
          this.columns[1] = data1;
          this.leve2region = res.data.data;
          this.$refs.uPicker.setColumnValues(1, data1);
          regionList({
            parentCode: res.data.data[0].code,
          }).then((res) => {
            let data1 = [];
            res.data.data.map((item) => {
              data1.push(item.name);
            });
            this.columns[2] = data1;
            this.leve3region = res.data.data;
            this.$refs.uPicker.setColumnValues(2, data1);
            this.loading = false;
          });
        });
      }
      uni.hideLoading();
    },
    changeHandler(e) {
      this.loading = true;
      if (e.columnIndex == 0) {
        let index = e.index;
        let parentCode = this.levelregion[index].code;
        regionList({
          parentCode,
        }).then((res) => {
          let data1 = [];
          res.data.data.map((item) => {
            data1.push(item.name);
          });
          this.columns[1] = data1;
          this.leve2region = res.data.data;
          this.$refs.uPicker.setColumnValues(1, data1);
          regionList({
            parentCode: res.data.data[0].code,
          }).then((res) => {
            let data1 = [];
            res.data.data.map((item) => {
              data1.push(item.name);
            });
            this.columns[2] = data1;
            this.leve3region = res.data.data;
            this.$refs.uPicker.setColumnValues(2, data1);
            this.loading = false;
          });
        });
      }
      if (e.columnIndex == 1) {
        let index = e.index;
        let parentCode = this.leve2region[index].code;
        regionList({
          parentCode,
        }).then((res) => {
          let data1 = [];
          res.data.data.map((item) => {
            data1.push(item.name);
          });
          this.columns[2] = data1;
          this.leve3region = res.data.data;
          this.$refs.uPicker.setColumnValues(2, data1);
          this.loading = false;
        });
      }
      if (e.columnIndex == 2) {
        this.loading = false;
      }
    },
    defaultChange(e) {
      this.from.isDefault = !this.from.isDefault;
    },
    showPopup() {
      this.show = true;
    },
    gourl(url) {
      go(url);
    },

    back() {
      back();
    },

    backtime() {
      backtime();
    },
    confirm(e) {
      console.log(e);
      let data1 = this.levelregion[e.indexs[0]];
      let data2 = this.leve2region[e.indexs[1]];
      let data3 = this.leve3region[e.indexs[2]];
      console.log(data1);
      console.log(data2);
      console.log(data3);
      this.from.province = data1.name;
      this.from.city = data2.name;
      this.from.district = data3.name;
      this.show = false;
    },

    /**
     * 打开地图选择地址
     */

    chooseLocation() {
      let that = this;
      uni.chooseLocation({
        useSecureNetwork: false,
        success: (res) => {
          console.log(res);
          let { latitude, longitude, address } = res;
          let key = "LA3BZ-MY6O6-UUUSE-EUV43-T6QHH-DOFSI";
          let location = `${latitude},${longitude}`;
          this.from.lat = latitude;
          this.from.lng = longitude;
          this.from.address = address;
          // #ifdef H5
          this.$jsonp(config.apisUrl, {
            key,
            location,
            output: "jsonp",
          }).then((res) => {
            console.log(res);
            if (res.status == 0) {
              let data = res.result.address_component;
              let province =
                Object.prototype.toString.call(data.province) ==
                "[object String]"
                  ? data.province
                  : "";
              let city =
                Object.prototype.toString.call(data.city) == "[object String]"
                  ? data.city
                  : data.province;
              let district =
                Object.prototype.toString.call(data.district) ==
                "[object String]"
                  ? data.district
                  : Object.prototype.toString.call(data.city) ==
                    "[object String]"
                  ? data.city
                  : data.province;
              this.from.province = province;
              this.from.city = city;
              this.from.district = district;
              // this.from.address = res.result.address;
            } else {
              uni.showModal({
                title: "提示",
                content: "解析地址失败" + res.message,
                showCancel: false,
              });
            }
          });
          // #endif

          // #ifdef MP-WEIXIN
          uni.request({
            url: config.apisUrl,
            data: {
              key,
              location,
              output: "jsonp",
            },
            method: "GET",
            success: (data) => {
              console.log(data);
              let res = data.data.substring(
                "QQmap&&QQmap(".length,
                data.data.length - 2
              );
              console.log(res);
              res = JSON.parse(res);
              if (res.status == 0) {
                let data = res.result.address_component;
                let province =
                  Object.prototype.toString.call(data.province) ==
                  "[object String]"
                    ? data.province
                    : "";
                let city =
                  Object.prototype.toString.call(data.city) == "[object String]"
                    ? data.city
                    : data.province;
                let district =
                  Object.prototype.toString.call(data.district) ==
                  "[object String]"
                    ? data.district
                    : Object.prototype.toString.call(data.city) ==
                      "[object String]"
                    ? data.city
                    : data.province;
                this.from.province = province;
                this.from.city = city;
                this.from.district = district;
                // this.from.address = res.result.address;
              } else {
                uni.showModal({
                  title: "提示",
                  content: "解析地址失败" + res.message,
                  showCancel: false,
                });
              }
            },
            fail: (error) => {},
          });
          // #endif
        },
        fail: (err) => {
          console.log(err);
          msg(err.errMsg);
        },
      });
    },

    save() {
      let {
        consignee,
        mobile,
        province,
        address,
        provinceId,
        city,
        cityId,
        district,
        districtId,
        isDefault,
        lat,
        lng,
      } = this.from;
      if (consignee.trim() == "") {
        uni.showToast({
          title: "请输入收货人",
          mask: true,
          icon: "none",
        });
        return false;
      }
      if (mobile.trim() == "") {
        uni.showToast({
          title: "请输入手机号码",
          mask: true,
          icon: "none",
        });
        return false;
      }
      let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!myreg.test(mobile)) {
        uni.showToast({
          title: "手机号格式不正确",
          mask: true,
          icon: "none",
        });
        return false;
      }
      if (province.trim() == "") {
        uni.showToast({
          title: "请选择区域",
          mask: true,
          icon: "none",
        });
        return false;
      }
      if (address.trim() == "") {
        uni.showToast({
          title: "请输入详细地址",
          mask: true,
          icon: "none",
        });
        return false;
      }
      if (this.options.id) {
        addressSubmit({
          id: this.options.id,
          consignee,
          mobile,
          province,
          provinceId,
          city,
          cityId,
          district,
          districtId,
          isDefault: isDefault ? 1 : 0,
          address,
          lat,
          lng,
        }).then((res) => {
          back(1);
          msg(res.data.msg);
        });
      } else {
        addressSubmit({
          id: "",
          consignee,
          mobile,
          province,
          provinceId,
          city,
          cityId,
          district,
          districtId,
          isDefault: isDefault ? 1 : 0,
          address,
          lat,
          lng,
        }).then((res) => {
          back(1);
          msg(res.data.msg);
        });
      }
    },
  },
  /**** 方法层 ****/

  /***下拉刷新 触底刷新***/
  async onReachBottom() {},
  async onPullDownRefresh() {
    uni.stopPullDownRefresh();
  },
  /***下拉刷新 触底刷新***/
};
</script>

<style>
/* #ifdef MP-WEIXIN */
page {
  background: #f5f5f5;
}

/* #endif */
</style>

<style scoped lang="scss">
page {
  background: #f5f5f5;
}

.infobox1 {
  background: #ffffff;
  margin: 30rpx 30rpx 0;
  padding: 30rpx 30rpx 0;
  border-radius: 30rpx;
}

.infobox1 .info1 {
  height: 100rpx;
  padding: 24rpx 0;
  // border-bottom: 1px solid red;
  border-bottom: 1px solid #f5f5f5;
}

.infobox1 .info1 .label {
  font-style: normal;
  font-weight: 400;
  font-size: 24rpx;
  color: #525252;
}

.infobox1 .info1 .input {
  position: relative;
  margin: 24rpx 0 0;
  // width: calc(100% - 200rpx);
}

.infobox1 .info1 .placeholder {
  font-style: normal;
  font-weight: 400;
  font-size: 32rpx;
  color: #858585;
}

.infobox1 .info1 .input input {
  // text-align: right;
  width: 100%;
  font-style: normal;
  font-weight: 400;
  font-size: 32rpx;
  color: #1f1f1f;
}

.infobox1 .info1 .icon {
  width: 100rpx;
  height: 60rpx;
}

.infobox1 .info1 .input .right {
  width: 40rpx;
  // height: 24rpx;
  position: absolute;
  top: 0rpx;
  right: 0;
}

.btn {
  width: 600rpx;
  height: 88rpx;
  text-align: center;
  line-height: 88rpx;
  color: #ffffff;
  font-style: normal;
  font-weight: 400;
  font-size: 28rpx;
  background: #5ccedd;
  border-radius: 44rpx;
  margin: 30rpx auto 0;
  position: relative;
}

.globalBtn {
  position: fixed;
  bottom: 0;
  width: 100%;
  background: #fff;
  padding: 0 0 50rpx 0;

  .block1 {
    margin: 10rpx 30rpx 0;
    background: var(--view-theme);
    border-radius: 40rpx;
    text-align: center;
    height: 80rpx;
    line-height: 80rpx;
    color: #fff;
    font-size: 28rpx;
    font-weight: bold;
  }
}

image {
  width: 100%;
  height: 100%;
}
</style>
